package com.home.qh.listener;

import org.hibernate.envers.RevisionListener;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.home.qh.Constants;
import com.home.qh.model.AuditRevision;
import com.home.qh.model.User;

public class AuditListener implements RevisionListener {
    public void newRevision(Object revisionEntity) {
        AuditRevision revEntity = (AuditRevision) revisionEntity;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        User user = getCurrentUser(auth);
        if(user != null) {
            revEntity.setUsername(user.getUsername());
        } else {
            revEntity.setUsername(Constants.USER_SYSTEM);
        }
    }

    private User getCurrentUser(Authentication auth) {
        User currentUser = null;
        if (auth != null && auth.getPrincipal() instanceof UserDetails) {
            currentUser = (User) auth.getPrincipal();
        } else if (auth != null && auth.getDetails() instanceof UserDetails) {
            currentUser = (User) auth.getDetails();
        }
        return currentUser;
    }
}
